<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vision Analyzer - 管理界面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .nav-tabs {
            display: flex;
            background: #f8f9fa;
            border-bottom: 2px solid #e0e0e0;
        }

        .nav-tab {
            flex: 1;
            padding: 15px 20px;
            text-align: center;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 1rem;
            font-weight: 500;
            color: #666;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
        }

        .nav-tab.active {
            color: #4facfe;
            border-bottom-color: #4facfe;
            background: white;
        }

        .nav-tab:hover {
            color: #4facfe;
        }

        .content {
            padding: 40px;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .provider-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            border: 2px solid transparent;
            transition: border-color 0.3s ease;
        }

        .provider-card.active {
            border-color: #4facfe;
        }

        .provider-card h3 {
            color: #4facfe;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .provider-actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.3);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%);
        }

        .btn-secondary {
            background: #6c757d;
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 0.8rem;
        }

        .model-list {
            margin-top: 15px;
            max-height: 200px;
            overflow-y: auto;
        }

        .model-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background: white;
            border-radius: 4px;
            margin-bottom: 5px;
            border: 1px solid #e0e0e0;
        }

        .model-item:hover {
            border-color: #4facfe;
        }

        .add-model-form {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .add-model-form input {
            flex: 1;
            padding: 8px 12px;
            border: 2px solid #e0e0e0;
            border-radius: 4px;
            font-size: 0.9rem;
        }

        .add-model-form input:focus {
            outline: none;
            border-color: #4facfe;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4facfe;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-active {
            background: #28a745;
        }

        .status-inactive {
            background: #6c757d;
        }

        .back-link {
            position: absolute;
            top: 20px;
            left: 20px;
            color: white;
            text-decoration: none;
            font-size: 1rem;
            opacity: 0.9;
            transition: opacity 0.3s ease;
        }

        .back-link:hover {
            opacity: 1;
        }

        .current-status {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #4facfe;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <a href="/" class="back-link">← 返回配置</a>
            <h1>🔧 Vision Analyzer 管理界面</h1>
            <p>管理您的LLM服务商和模型配置</p>
        </div>

        <div class="nav-tabs">
            <button class="nav-tab active" onclick="showTab('providers')">服务商管理</button>
            <button class="nav-tab" onclick="showTab('models')">模型管理</button>
        </div>

        <div class="content">
            <div class="alert alert-info" id="infoAlert">
                <strong>提示：</strong>您可以在这里管理服务商和模型配置
            </div>

            <div class="alert alert-success" id="successAlert">
                <strong>成功！</strong>操作已完成
            </div>

            <div class="alert alert-error" id="errorAlert">
                <strong>错误：</strong><span id="errorMessage"></span>
            </div>

            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在处理请求...</p>
            </div>

            <!-- 服务商管理 -->
            <div id="providers" class="tab-content active">
                <div class="current-status" id="currentStatus">
                    <h4>当前状态</h4>
                    <p id="currentProviderText">加载中...</p>
                </div>

                <h3>已配置的服务商</h3>
                <div id="providersList"></div>
            </div>

            <!-- 模型管理 -->
            <div id="models" class="tab-content">
                <div id="modelManagement">
                    <h3>模型管理</h3>
                    <div id="modelsContent"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentTab = 'providers';

        function showTab(tabName) {
            // 隐藏所有tab内容
            const contents = document.querySelectorAll('.tab-content');
            contents.forEach(content => content.classList.remove('active'));

            // 移除所有tab的active类
            const tabs = document.querySelectorAll('.nav-tab');
            tabs.forEach(tab => tab.classList.remove('active'));

            // 显示选中的tab
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');

            currentTab = tabName;

            // 隐藏所有提示信息
            hideAllAlerts();

            // 加载对应的数据
            if (tabName === 'providers') {
                loadProviders();
            } else if (tabName === 'models') {
                loadModelManagement();
            }
        }

        function hideAllAlerts() {
            document.getElementById('infoAlert').style.display = 'none';
            document.getElementById('successAlert').style.display = 'none';
            document.getElementById('errorAlert').style.display = 'none';
        }

        function showAlert(type, message) {
            hideAllAlerts();
            const alert = document.getElementById(type + 'Alert');
            if (type === 'error' && message) {
                document.getElementById('errorMessage').textContent = message;
            }
            alert.style.display = 'block';
        }

        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
        }

        async function loadProviders() {
            showLoading(true);
            try {
                const response = await fetch('/list-providers');
                const data = await response.json();

                if (data.success) {
                    renderProviders(data.providers);
                    await loadCurrentStatus();
                } else {
                    showAlert('error', data.error);
                }
            } catch (error) {
                // 检测服务关闭的情况
                if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
                    showServerShutdownMessage();
                } else {
                    showAlert('error', '网络错误: ' + error.message);
                }
            } finally {
                showLoading(false);
            }
        }

        async function loadCurrentStatus() {
            try {
                const response = await fetch('/list-providers');
                const data = await response.json();

                if (data.success) {
                    // 这里应该显示当前provider，但暂时显示基本信息
                    document.getElementById('currentProviderText').innerHTML =
                        '已配置 ' + data.providers.length + ' 个服务商';
                }
            } catch (error) {
                console.error('加载状态失败:', error);
            }
        }

        function renderProviders(providers) {
            const container = document.getElementById('providersList');

            if (providers.length === 0) {
                container.innerHTML = '<p>暂无配置的服务商，请先<a href="/">添加配置</a></p>';
                return;
            }

            container.innerHTML = providers.map(provider => `
                <div class="provider-card">
                    <h3>
                        <span>
                            <span class="status-indicator status-active"></span>
                            ${provider.name}
                        </span>
                        <div class="provider-actions">
                            <button class="btn btn-small" onclick="switchProvider('${provider.name}')">切换</button>
                            <button class="btn btn-danger btn-small" onclick="deleteProvider('${provider.name}')">删除</button>
                        </div>
                    </h3>
                    <p><strong>API地址:</strong> ${provider.baseUrl}</p>
                    <p><strong>API密钥:</strong> ${provider.apiKey}</p>
                    <div class="model-list" id="models-${provider.name}">
                        <button class="btn btn-small btn-secondary" onclick="loadProviderModels('${provider.name}')">
                            加载模型列表
                        </button>
                    </div>
                </div>
            `).join('');
        }

        async function loadProviderModels(providerName) {
            const container = document.getElementById(`models-${providerName}`);
            container.innerHTML = '<p>加载中...</p>';

            try {
                const response = await fetch(`/list-models?provider=${providerName}`);
                const data = await response.json();

                if (data.success) {
                    renderProviderModels(providerName, data.models);
                } else {
                    container.innerHTML = `<p style="color: red;">加载失败: ${data.error}</p>`;
                }
            } catch (error) {
                // 检测服务关闭的情况
                if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
                    // 不显示错误，因为主页面会处理服务关闭的情况
                    container.innerHTML = `<p style="color: #6c757d;">服务器已关闭，配置已完成</p>`;
                } else {
                    container.innerHTML = `<p style="color: red;">网络错误: ${error.message}</p>`;
                }
            }
        }

        function renderProviderModels(providerName, models) {
            const container = document.getElementById(`models-${providerName}`);

            if (models.length === 0) {
                container.innerHTML = '<p>暂无可用模型</p>';
                return;
            }

            container.innerHTML = `
                <h4>可用模型</h4>
                <div class="model-list">
                    ${models.map(model => `
                        <div class="model-item">
                            <span>${model.id || model}</span>
                            <button class="btn btn-small btn-secondary" onclick="switchModel('${providerName}', '${model.id || model}')">使用</button>
                        </div>
                    `).join('')}
                </div>
                <div class="add-model-form">
                    <input type="text" id="newModel-${providerName}" placeholder="输入新模型ID">
                    <button class="btn btn-small" onclick="addModel('${providerName}')">添加</button>
                </div>
            `;
        }

        async function loadModelManagement() {
            const container = document.getElementById('modelsContent');
            container.innerHTML = '<p>请先在服务商管理中选择一个服务商查看模型</p>';
        }

        async function switchProvider(providerName) {
            if (!confirm(`确定要切换到 ${providerName} 吗？`)) return;

            showLoading(true);
            try {
                const response = await fetch('/switch-provider', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ provider: providerName })
                });

                const data = await response.json();
                if (data.success) {
                    showAlert('success', data.message);
                    await loadCurrentStatus();
                } else {
                    showAlert('error', data.error);
                }
            } catch (error) {
                showAlert('error', '网络错误: ' + error.message);
            } finally {
                showLoading(false);
            }
        }

        async function deleteProvider(providerName) {
            if (!confirm(`确定要删除 ${providerName} 吗？此操作不可撤销！`)) return;

            showLoading(true);
            try {
                const response = await fetch('/delete-provider', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ provider: providerName })
                });

                const data = await response.json();
                if (data.success) {
                    showAlert('success', data.message);
                    await loadProviders();
                } else {
                    showAlert('error', data.error);
                }
            } catch (error) {
                showAlert('error', '网络错误: ' + error.message);
            } finally {
                showLoading(false);
            }
        }

        async function switchModel(providerName, modelId) {
            if (!confirm(`确定要切换到 ${providerName}-${modelId} 吗？`)) return;

            showLoading(true);
            try {
                const response = await fetch('/switch-model', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ provider: providerName, model: modelId })
                });

                const data = await response.json();
                if (data.success) {
                    showAlert('success', data.message);
                    await loadCurrentStatus();
                } else {
                    showAlert('error', data.error);
                }
            } catch (error) {
                showAlert('error', '网络错误: ' + error.message);
            } finally {
                showLoading(false);
            }
        }

        async function addModel(providerName) {
            const input = document.getElementById(`newModel-${providerName}`);
            const modelId = input.value.trim();

            if (!modelId) {
                showAlert('error', '请输入模型ID');
                return;
            }

            showLoading(true);
            try {
                const response = await fetch('/add-model', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ provider: providerName, modelId: modelId })
                });

                const data = await response.json();
                if (data.success) {
                    showAlert('success', data.message);
                    input.value = '';
                    await loadProviderModels(providerName);
                } else {
                    showAlert('error', data.error);
                }
            } catch (error) {
                showAlert('error', '网络错误: ' + error.message);
            } finally {
                showLoading(false);
            }
        }

        // 页面加载完成后加载服务商数据
        document.addEventListener('DOMContentLoaded', function() {
            loadProviders();
        });
    </script>
</body>
</html>